

import 'dart:ui';

import 'package:bot_toast/bot_toast.dart';
import 'package:dolqun_movies/Entities/FilterPreDataResult.dart';
import 'package:dolqun_movies/Entities/LatestMovies.dart';
import 'package:dolqun_movies/Entities/Movie.dart';
import 'package:dolqun_movies/StateManagement/ModelProvider.dart';
import 'package:dolqun_movies/UI/Pages/Models/ColorThemeModel.dart';
import 'package:dolqun_movies/UI/Pages/Models/MainModel.dart';
import 'package:dolqun_movies/UI/Widgets/DolqunAppBar.dart';
import 'package:dolqun_movies/UI/Widgets/MovieView.dart';
import 'package:dolqun_movies/UI/Widgets/MyAnimatedRoute.dart';
import 'package:dolqun_movies/UI/Widgets/VideoPlayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:video_player/video_player.dart';
import 'package:dolqun_movies/Extensions.dart';
import 'HomePage/DetailsPage.dart';
import 'Models/AnimationKeysModel.dart';
import 'Models/CacheManagerModel.dart';

class FilterPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _FilterPageState();
  }
}

class _FilterPageState extends State<FilterPage> with AutomaticKeepAliveClientMixin {
  Future<List<FilterPreData>> _preData;
  FilterPreData _selectedLevel0 = null;
  List<FilterLevel0> _selectedLevels;
  var _controller = ScrollController();
  var _oldPosition = 0.0;
  void Function() _loadMoreNotifier;

  @override
  void initState() {
    this._controller.addListener(this._scrollListener);
    super.initState();
  }
  @override
  void dispose() {
    this._controller.removeListener(this._scrollListener);
    super.dispose();
  }

  void _scrollListener() {
    var currentPosition = this._controller.position.extentAfter;
    if (_oldPosition == currentPosition) return;
    _oldPosition = currentPosition;
    if (_oldPosition == 0) {
      this._loadMoreNotifier?.call();
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    var keyModel = ModelContainer.of<AnimationKeysModel>(context).model;
    var keyOfContainer = keyModel.searchIconKeys[2].keyOfParent;
    keyModel.favoriteIconKeys[2].keyOfParent = keyOfContainer;
    keyModel.cartIconKeys[2].keyOfParent = keyOfContainer;
    keyModel.accountIconKeys[2].keyOfParent = keyOfContainer;

//    keyModel.settingsIconKeys[2].keyOfParent = keyModel.shareIconKeys[2].keyOfParent = keyOfContainer;
    var cacheManager = ModelContainer.of<CacheManagerModel>(context).model.cacheManager;
    var model = ModelContainer.of<MainModel>(context).model;
    var themeModel = ModelContainer.of<ColorThemeModel>(context).model;

    Widget buildingWidget = Stack(
      children: <Widget>[
        Positioned.fill(
          top: 50.0,
          child: FutureBuilder<List<FilterPreData>>(
            future: _preData ??= model.api.getFilterPreData(),
            builder: (context, snapshot){
              void selectFirstFilterElements(){
                _selectedLevels = List<FilterLevel0>.generate(_selectedLevel0.items.length, (index) => _selectedLevel0.items[index].items[0]);
              }
              if (snapshot.hasError) return Center(child: Text(snapshot.error.toString()));
              if (snapshot.hasData) {
                if (_selectedLevel0 == null) {
                  _selectedLevel0 = snapshot.data.first;
                  selectFirstFilterElements();
                }
                var level1Index = 0;
                return ListView(
                  controller: _controller,
                  children: <Widget>[
                    Wrap(
                      children: snapshot.data.map((level0) => _buildChip(
                          text: level0.name,
                          selectedColor: Colors.deepPurple,
                          onTap: (){
                            setState(() {
                              _selectedLevel0 = level0;
                              selectFirstFilterElements();
                            });
                          },
                          selected: level0.id == _selectedLevel0.id),
                      ).toList(),
                    ),
                    Column(
                      children: _selectedLevel0.items.map((level1){
                        var index = level1Index++;
                        return SizedBox(
                          width: double.infinity,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              Text(level1.name),
                              Wrap(
                                children: level1.items.map((level2) => _buildChip(
                                  text: level2.name,
                                  onTap: (){
                                    setState(() {
                                      _selectedLevels[index] = level2;
                                    });
                                  },
                                  selectedColor: Colors.deepPurple,
                                  selected: _selectedLevels[index]?.id == level2.id,
                                )).toList(),
                              ),
                            ],
                          ),
                        );
                      }).toList(),
                    ),
                    Builder(
                      builder: (context){
                        var movies = <Movie>[];
                        var pageIndex = 1;
                        return StatefulBuilder(
                          builder: (context, setState){
                            this._loadMoreNotifier = () => setState((){});
//                            var result = movies.groupBy((element) => element.id).values.map((e) => e.length);
//                            print(result);
                            BotToast.showLoading();
                            return FutureBuilder<LatestResponse>(
                              future: model.api.getFilteredMovies(this._selectedLevel0.id, this._selectedLevels.where((element) => element != null).map((e) => e.id).toList(), pageIndex++).then(
                                (result){
                                  movies = [...movies, ...result.data];
                                  BotToast.closeAllLoading();
                                  return Future.value(result);
                                }
                              ),
                              builder: (context, snapshot){
                                if (snapshot.hasError) return Center(child: Text(snapshot.error.toString(), style: TextStyle(color: Colors.red),),);
                                if (snapshot.hasData) {
                                  if (movies.isEmpty) return Center(child: Text("مەزمۇن تېپىلمىدى، باشقا تۈرلەرنى تاللاپ سىناپ بېقىڭ"),);
                                  return Wrap(
                                    alignment: WrapAlignment.center,
                                    children: movies.map((e) => _buildMovieItem(e, heroTagBuilder: (id) => "Item: $id",)).toList(),
                                  );
                                }
                                return Center(child: CircularProgressIndicator(),);
                              },
                            );
                          },
                        );
                      },
                    ),
                  ],
                );
              }
              return Center(child: CircularProgressIndicator());
            },
          ),
        ),
        Positioned(
          left: 0.0,
          top: 0.0,
          bottom: 0.0,
          width: 50.0,
          child: Center(
            child: ClipRRect(
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(20.0),
                bottomRight: Radius.circular(20.0),
              ),
              child: Container(
                constraints: BoxConstraints(
                    maxHeight: 250.0,
                    minHeight: 100.0
                ),
                width: double.infinity,
                color: Colors.white.withOpacity(0.04),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    SizedBox(width: double.infinity, height: 50.0, key: keyModel.accountIconKeys[2].keyOfWidget,),
                    SizedBox(width: double.infinity, height: 50.0, key: keyModel.searchIconKeys[2].keyOfWidget,),
                    SizedBox(width: double.infinity, height: 50.0, key: keyModel.cartIconKeys[2].keyOfWidget,),
                    SizedBox(width: double.infinity, height: 50.0, key: keyModel.favoriteIconKeys[2].keyOfWidget,),
                  ],
                ),
              ),
            ),
          ),
        ),
      ],
    );
    buildingWidget = Scaffold(
      key: keyOfContainer,
      backgroundColor: Colors.transparent,
      body: buildingWidget,
    );
    return buildingWidget;
  }

  Widget _buildChip({String text, void onTap(), bool selected = false, Color selectedColor}){
    return InkWell(
      splashColor: Colors.deepPurple,
      onTap: onTap,
      child: AnimatedContainer(
        duration: Duration(milliseconds: 300),
        decoration: BoxDecoration(
            color: selected ? selectedColor : Colors.white.withOpacity(0.04),
            borderRadius: BorderRadius.circular(8.0)
        ),
        padding: EdgeInsets.all(5.0),
        margin: EdgeInsets.all(3.0),
        child: Text(text, style: TextStyle(fontSize: 12.0),),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  Widget _buildMovieItem(Movie movie, {String heroTagBuilder(int id)}) {
    heroTagBuilder ??= (id) => id.toString();
    var tag = heroTagBuilder(movie.id);
    return Hero(
      tag: tag,
      child: MovieView(
        movie: movie,
        onTab: ()async {
          await Navigator.of(context).push(MyAnimatedRoute(builder: (context) => DetailsPage(movie: movie, heroTag: tag,)));
        },
      ),
    );
  }
}

